import org.apache.commons.logging.LogFactory
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import grails.util.Environment
import org.codehaus.groovy.grails.commons.ApplicationHolder

import org.weceem.auth.*
import org.weceem.content.*
import org.weceem.files.*

class BootStrap {

    def initialised = false

    def _log = LogFactory.getLog('org.weceem.BootStrap')

    def init = { servletContext ->
        def ctx = ApplicationHolder.application.mainContext

        setupSecurity(ctx)

        if (!initialised && (Environment.current != Environment.TEST)) {

            def role_user = null
            if (!Role.findByAuthority('ROLE_USER')) {
                role_user = new Role(authority: 'ROLE_USER').save(flush:true)
            }
            assert role_user

            def role_admin = null
            if (!Role.findByAuthority('ROLE_ADMIN')) {
                role_admin = new Role(authority: 'ROLE_ADMIN').save(flush:true)
            }
            assert role_admin

            def default_admin = null
            if (!User.findByUsername('admin')) {
                default_admin = new User(username: 'admin',
                        // password "admin" (SHA-512)
                        password: 'c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8de9077ec',
                        enabled: true, accountExpired: false, accountLocked: false, passwordExpired: false)
                        .save(flush:true)
            }
            assert default_admin
            if (role_user) UserRole.create(default_admin, role_user, true)
            if (role_admin) UserRole.create(default_admin, role_admin, true)

            // Make sure the upload dirs exist
            def uploadsDir = new File(servletContext.getRealPath(WcmContentFile.DEFAULT_UPLOAD_DIR))
            if (!uploadsDir.exists()) {
                uploadsDir.mkdirs()
            }

      }
    }

    def destroy = {
    }

    /**
     * Set up the cms plugin so it uses acegi for auth
     */
    private setupSecurity(context) {
        def authenticateService = context.springSecurityService
        context.wcmSecurityService.securityDelegate = [
            getUserName : { ->
                def princ = authenticateService.principal
                if (log.debugEnabled) {
                    log.debug "Weceem security getUserName callback - user principal is: ${princ} (an instance of ${princ?.class})"
                }
                if (princ instanceof String) {
                    return null
                } else {
                    return authenticateService.principal?.username
                }
            },
//            getUserEmail : { ->
//                def princ = authenticateService.principal()
//                if (log.debugEnabled) {
//                    log.debug "Weceem security getUserEmail callback - user principal is: ${princ} (an instance of ${princ?.class})"
//                }
//                if (princ instanceof String) {
//                    return null
//                } else {
//                    return authenticateService.principal?.email
//                }
//            },
//            getUserRoles : { -> authenticateService.principal.getAuthorities() ?: ['ROLE_GUEST'] },
            getUserRoles : { ->
                def auth = authenticateService.authentication
                if (auth) {
                    def authorities = auth.authorities
                    def auth_list = []
                    if (authorities) {
                        authorities.each {
                            if (it == "ROLE_ANONYMOUS") {
                                auth_list << "ROLE_GUEST"
                            } else {
                            auth_list << it
                            }
                        }
                        return auth_list
                    } else {
                        return ['ROLE_GUEST']
                    }
                } else {
                    return ['ROLE_GUEST']
                }
            },
            getUserPrincipal : { -> authenticateService.principal }
        ]
    }

}
